package com.example.scaffold_demo.ui;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.example.httplibrary.download.DownLoadManagerToos;
import com.example.scaffold_demo.R;
import com.example.scaffold_demo.base.BaseActivity;
import com.example.scaffold_demo.bean.ApkUpdateDataBean;
import com.example.scaffold_demo.common.Constant;
import com.example.scaffold_demo.common.EventConstant;
import com.example.scaffold_demo.http.download.DownloadApkService;
import com.example.scaffold_demo.utils.NetworkUtils;
import com.example.scaffold_demo.utils.PathFileUtil;
import com.example.scaffold_demo.utils.SPUtils;
import com.example.scaffold_demo.utils.Toos;
import com.example.scaffold_demo.widget.ToastUtils;
import com.example.scaffold_demo.widget.eventbus.EventBean;

import java.io.File;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Author: 李巷阳
 * Date: 2020/9/7
 * Description: 下载activity
 */
public class DownloadActivity extends BaseActivity {

    @BindView(R.id.bt_delect_file)
    Button startDownload;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_version)
    TextView txtVersion;
    @BindView(R.id.txt_size)
    TextView txtSize;
    @BindView(R.id.txt_notice)
    TextView txtNotice;
    @BindView(R.id.download_progress)
    ProgressBar downloadProgress;
    @BindView(R.id.btn_dialog_cancel)
    Button btnDialogCancel;
    @BindView(R.id.btn_dialog_sure)
    Button btnDialogSure;
    @BindView(R.id.ll_cancel_sure)
    LinearLayout llCancelSure;
    @BindView(R.id.txt_current_progress)
    TextView txtCurrentProgress;
    private ApkUpdateDataBean mApkUpdateDataBean;
    private String downloadUrl;
    private String downloadFileName;


    @Override
    protected void initTitle() {

    }

    @Override
    protected int setLayout() {
        return R.layout.activity_download;
    }

    protected void initView() {
        txtNotice.setText(mApkUpdateDataBean.getDesc());//更新描述
        txtSize.setText(mApkUpdateDataBean.getSize());//更新大小
        txtVersion.setText(mApkUpdateDataBean.getName());//更新版本号
        // 断点下载,获取当前下载的进入百分百比
        int progress = getCurrentProgress();
        downloadProgress.setProgress(progress);
        txtCurrentProgress.setText("" + progress);
        // 判断是否强制更新
        if (Constant.NEED_FORCE_UPDATE == mApkUpdateDataBean.getType()) {
            btnDialogCancel.setText("退出");
            btnDialogSure.setText("升级");
        } else {
            btnDialogCancel.setText("取消");
            btnDialogSure.setText("升级");
        }
        // 判断是否显示安装
        if (isShowInstall(downloadUrl, downloadFileName)) {
            downloadProgress.setProgress(100);
            txtCurrentProgress.setText(100 + "");
            downloadProgress.setVisibility(View.VISIBLE);
            btnDialogSure.setText("安装");
        }
    }

    protected void initData() {
        mApkUpdateDataBean = new ApkUpdateDataBean();
        mApkUpdateDataBean.setName("3.0.0");// 更新版本
        mApkUpdateDataBean.setCode(1003000000);// 更新version code
        mApkUpdateDataBean.setType(1);// 是否强制更新
        mApkUpdateDataBean.setScope(1);
        mApkUpdateDataBean.setDesc("1.推出萌股看板娘\\r\\n2.全新的新手引导\\r\\n3.新增角色养成任务\\r\\n4.新增应援动态展示\\r\\n5.番剧详情页支持跳转到视频播放地址\"");// 下载详情
        mApkUpdateDataBean.setUrl("http://download.moego.net/version/apk/wdnrV823zfh2mGOzGL8CVYn1CqwYhUjc.apk");// 下载路径
        mApkUpdateDataBean.setSize("100.99");// 显示下载大小

        downloadUrl = mApkUpdateDataBean.getUrl();//下载地址
        downloadFileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1);// 下载name


    }

    @OnClick({R.id.bt_delect_file, R.id.btn_dialog_cancel, R.id.btn_dialog_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            // 删除按钮
            case R.id.bt_delect_file:
                deleteOldApk();
                btnDialogSure.setText("升级");
                txtCurrentProgress.setText("0");
                downloadProgress.setProgress(0);
                break;
            // 取消或者退出
            case R.id.btn_dialog_cancel:
                // 如果是强制更新,
                if (Constant.NEED_FORCE_UPDATE == mApkUpdateDataBean.getType()) {
                    Toast.makeText(this, "退出app", Toast.LENGTH_SHORT).show();
                } else {
                    DownLoadManagerToos.getInstance().setStop(true);
                }
                break;
            // 确定
            case R.id.btn_dialog_sure:
                if (!NetworkUtils.isConnected(this)) {
                    ToastUtils.showShortToast("网络异常，请检查网络设置");
                    return;
                }
                // 强制更新逻辑
                if (Constant.NEED_FORCE_UPDATE == mApkUpdateDataBean.getType()) {
                    ToastUtils.showShortToast("萌股正在下载...");
                    if (Toos.isServiceRunning(DownloadApkService.class.getName())) {
                        ToastUtils.showShortToast("萌股正在下载,请稍等...");
                        return;
                    }
                    // 开始下载
                    startDownloadIntentService(downloadUrl, downloadFileName, 1);
                }
                // 非强制更新逻辑
                else {
                    ToastUtils.showShortToast("萌股更新包正在后台下载...");
                    if (Toos.isServiceRunning(DownloadApkService.class.getName())) {
                        ToastUtils.showShortToast("萌股更新包正在后台下载...");
                        return;
                    }
                    Toast.makeText(this, "萌股更新包正在后台下载...", Toast.LENGTH_LONG).show();
                    // 开始下载
                    startDownloadIntentService(downloadUrl, downloadFileName, 1);
                }
                break;
        }
    }
    public final static String  INTENT_DOWNLOAD_URL="intent_download_url";
    public final static String  INTENT_NOTIFY_ID="intent_notify_id";
    public final static String  INTENT_DOWNLOAD_FILE_NAME="intent_download_file_name";
    public final static String  INTENT_IS_OPEN_NOTIFY="intent_is_open_notify";

    /**
     * 开启service下载
     *
     * @param downloadUrl
     * @param downloadFileName
     */
    private void startDownloadIntentService(String downloadUrl, String downloadFileName, int is_open_notify) {
        Intent intent = new Intent(getApplicationContext(), DownloadApkService.class);
        Bundle bundle = new Bundle();
        bundle.putString(INTENT_DOWNLOAD_URL, downloadUrl);
        bundle.putInt(INTENT_NOTIFY_ID, 10);
        bundle.putString(INTENT_DOWNLOAD_FILE_NAME, downloadFileName);
        bundle.putInt(INTENT_IS_OPEN_NOTIFY, is_open_notify);
        intent.putExtras(bundle);
        this.startService(intent);
    }


    @Override
    public void showError(String msg) {

    }


    @Override
    protected boolean isRegisterEventBus() {
        return true;
    }


    @Override
    protected void receiveEvent(EventBean event) {
        super.receiveEvent(event);
        switch (event.getCode()) {
            case EventConstant.VersionUpdateProgressBar:
                if (downloadProgress != null) {
                    downloadProgress.setVisibility(View.VISIBLE);
                    int progress = (int) event.getData();
                    downloadProgress.setProgress(progress);
                    txtCurrentProgress.setText(progress + "");
                    if (btnDialogSure != null) {
                        if (progress >= 100) {
                            btnDialogSure.setText("安装");
                        }
                    }
                }
                break;
        }
    }


    /**
     * 断点下载,获取当前下载的进入百分百比
     *
     * @return
     */
    public int getCurrentProgress() {
        // 获取下载本地的路径
        String loadFilePath = Constant.DEFAULT_DOWNLOAD_PATH + "/" + downloadFileName;
        if (downloadUrl != null) {
            final File file = new File(loadFilePath);
            if (file.exists()) {
                long range = (long) SPUtils.get(downloadUrl, 0L);
                int progress = (int) (range * 100 / file.length());
                return progress;
            }
        }
        return 0;
    }

    /**
     * 删除之前升级时下载的老的 apk 文件
     */
    public static void deleteOldApk() {
        String loadFilePath = Constant.DEFAULT_DOWNLOAD_PATH + "/";
        final File apkDir = new File(loadFilePath);
        if (apkDir == null || apkDir.listFiles() == null || apkDir.listFiles().length == 0) {
            return;
        }
        // 删除文件
        deleteFile(apkDir);
    }

    /**
     * 删除文件或文件夹
     *
     * @param file
     */
    static void deleteFile(File file) {
        try {
            if (file == null || !file.exists()) {
                return;
            }

            if (file.isDirectory()) {
                File[] files = file.listFiles();
                if (files != null && files.length > 0) {
                    for (File f : files) {
                        if (f.exists()) {
                            if (f.isDirectory()) {
                                deleteFile(f);
                            } else {
                                f.delete();
                            }
                        }
                    }
                }
            } else {
                file.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isShowInstall(String downloadUrl, String downloadFileName) {
        final File file = new File(PathFileUtil.getDownloadFilePath(getApplication()) + "/" + downloadFileName);
        long range = 0;
        int progress = 0;
        if (file.exists()) {
            range = (long) SPUtils.get(downloadUrl, 0L);
            progress = (int) (range * 100 / file.length());
            if (range == file.length()) {
                return true;
            }
        }
        return false;
    }
}